package com.gmrz.uap.config;

import com.gmrz.uap.TenantMapper;
import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.MybatisFlexBootstrap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.sql.DataSource;

/**
 * @author Wang Haifeng
 */
@WebListener
public class SystemConfigListeners implements ServletContextListener {

    private static final Logger log = LoggerFactory.getLogger(SystemConfigListeners.class);


    @Override
    public void contextInitialized(ServletContextEvent sce) {
        log.info("SystemConfigListeners contextInitialized");

        try {
            SentinelConfig.configureFlowRules();
            
            Context ctx = new InitialContext();
            Object datasourceCoreRef = ctx.lookup("java:comp/env/jdbc/fidods"); //引用数据源
            DataSource coreDs = (DataSource) datasourceCoreRef;
            Object datasourceLogRef = ctx.lookup("java:comp/env/jdbc/fidologds"); //引用数据源
            DataSource logDs = (DataSource) datasourceLogRef;


            FlexGlobalConfig globalConfig = FlexGlobalConfig.getDefaultConfig();
            globalConfig.setPrintBanner(false);

            MybatisFlexBootstrap.getInstance()
                    .setDataSource("coreDs", coreDs)
                    .addDataSource("logDs", logDs)
                    .addMapper(TenantMapper.class)
                    .start();

            log.info("MybatisFlexBootstrap[Mappers]: {}", MybatisFlexBootstrap.getInstance().getMappers());

        } catch (NamingException e) {
            log.error("初始化数据库资源出现异常", e);
        }

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        log.info("SystemConfigListeners contextDestroyed");
    }
}
